<?php
/**
 * 奖品类文件
 * 作者：刘单风
 * 最后修改时间：2018-11-15
 * 版权：医库PHP小组
 */

namespace app\model;
use think\Model;
use think\Db;

class Luckprizes extends Model
{
    /**
     * 用户参与抽奖记录数
     * @param $userid 用户id
     * @param int $datatype 0参与总数;1中奖总数
     */
    public function joincount($userid,$datatype=0)
    {
        $where = [
            'user_id' => $userid
        ];
        if ($datatype) {
            $where['is_win'] = [1, 2];
        }
        $count = Db::table('luck_join')
            ->where($where)
            ->count();
        return $count;
    }

    /**
     * 创建抽奖个数
     * @param $userid
     */
    public function createcount($userid)
    {
        $count = Db::table('luck_prizes')
            ->where('user_id',$userid)
            ->count();
        return $count;
    }

    /**
     * 获取中奖记录
     * @param $userid
     */
    public function winrecord($userid,$cpage)
    {
        $where = [
            'user_id' => $userid,
            'is_win' => [1, 2]
        ];
        //奖品id集合
        $prizeids = Db::table('luck_join')
            ->field('prize_id')
            ->where($where)
            ->column('prize_id');

        $prizedata = Db::table('luck_prizes')
            ->field('id,prize_title,prize_img,open_time,full_num,sponsor_id,prize_num,prize_type')
            ->where('id', 'in', $prizeids)
            ->page($cpage, 10)
            ->order('open_time desc')
            ->select();
        $result = $this->commonHandle($prizedata, 0);

        return $result;
    }

    /**
     * 我创建的抽奖列表
     * @param $userid 用户id
     * @param $datatype 0未开奖;1已结束
     * @return mixed
     */
    public function mycreate($userid,$datatype,$cpage)
    {
        $prizedata = Db::table('luck_prizes')
            ->field('id,prize_title,prize_img,open_time,full_num,prize_num,prize_type')
            ->where('user_id', $userid)
            ->where('is_logicdel', 0)
            ->where('is_open', $datatype)
            ->page($cpage,10)
            ->order('id desc')
            ->select();
        $result = $this->commonHandle($prizedata, 1);
        return $result;
    }

    /**
     * 我参与的列表
     * @param $datatype 0未开奖;1已结束
     * @return mixed
     */
    public function myjoin($userid,$datatype,$cpage)
    {
        if (empty($datatype)) {
            //按照参与时间倒序排列
            //奖品id集合
            $prizeids = Db::table('luck_join')
                ->field('prize_id')
                ->where('user_id', $userid)
                ->order('id desc')
                ->column('prize_id');
            $prizedata = Db::table('luck_prizes')
                ->field('id,prize_title,prize_img,open_time,full_num,sponsor_id,prize_num,prize_type')
                ->where('id', 'in', $prizeids)
                ->where('is_logicdel', 0)
                ->where('is_open', $datatype)
                ->page($cpage, 10)
                ->order('id', $prizeids)
                ->select();
        } else {
            //奖品id集合
            $prizeids = Db::table('luck_join')
                ->field('prize_id')
                ->where('user_id', $userid)
                ->column('prize_id');
            $prizedata = Db::table('luck_prizes')
                ->field('id,prize_title,prize_img,open_time,full_num,sponsor_id,prize_num,prize_type')
                ->where('id', 'in', $prizeids)
                ->where('is_logicdel', 0)
                ->where('is_open', $datatype)
                ->page($cpage, 10)
                ->order('open_time desc')
                ->select();
        }

        $result = $this->commonHandle($prizedata, 0);
        return $result;
    }

    /**
     * 首页的精选奖品
     */
    public function indexprize($userid)
    {
        $prizedata = Db::table('luck_prizes')
            ->field('id,prize_title,prize_img,open_time,full_num,sponsor_id,prize_num,prize_type')
            ->where('sponsor_id', '>', 0)
            ->where('is_open', 0)
            ->where('is_logicdel', 0)
            ->where('publish_time','<=', time())
            ->order('sort_num asc')
            ->order('create_time desc')
            ->select();
        $result = $this->commonHandle($prizedata, 0, $userid);
        return $result;
    }


    /**
     * 已开奖数据列表
     * @param $cpage 请求页码
     */
    public function openprize($cpage=1,$userid)
    {
        $prizedata = Db::table('luck_prizes')
            ->field('id,prize_title,prize_img,open_time,full_num,sponsor_id,prize_num,prize_type')
            ->where('sponsor_id', '>', 0)
            ->where('is_open', 1)
            ->where('is_logicdel', 0)
            ->order('open_time desc')
            ->page($cpage, 10)
            ->select();
        $opencount=0;
        if($cpage==1){
            //获取已开奖总数
            $opencount=Db::table('luck_prizes')
                ->where('sponsor_id', '>', 0)
                ->where('is_open', 1)
                ->where('is_logicdel', 0)
                ->count();
        }
        $result = $this->commonHandle($prizedata, 0, $userid);
        $datareturn=array(
            'openprize'=>$result,
            'opencount'=>$opencount
        );
        return $datareturn;
    }

    //定时程序获取奖品名称使用
    public function prizedetailmsg($prizeid)
    {
        //获取奖品名称
        $prizename = Db::table('luck_prizes')
            ->field('prize_title')
            ->where('id', $prizeid)
            ->value('prize_title');
        return $prizename;
    }

    /**
     * 获取奖品详情
     * @param $userid 用户id
     * @param $prizeid 奖品id
     */
    public function prizedetail($userid,$prizeid,$inviteid=0)
    {
        $detail = Db::table('luck_prizes')
            ->field('id,prize_title,prize_img,open_time,full_num,sponsor_id,prize_msg,prize_num,prize_type,user_id,is_open')
            ->where('id', $prizeid)
            ->find();
        if($detail['open_time']){
            $detail['true_open_time'] = date("Y-m-d H:i", $detail['open_time']);
        }else {
            $detail['true_open_time'] = "";
        }

        $detail['disclaimer'] = "第三方个人发起的抽奖活动，由第三方自行负责后续工作，抽奖用户本人已知晓规则，本平台不承担任何相关责任。";
        if ($detail['full_num']) {
            $detail['open_time'] = "参与人数达到{$detail['full_num']}人自动开奖";
        } else {
            $detail['open_time'] = date("m月d日 H:i", $detail['open_time']) . " 开奖";
        }
        //用户是否参与该抽奖
        $is_join = $this->isjoin($userid, $prizeid);
        $detail['is_join'] = $is_join ? 1 : 0;
        //获取赞助商
        if ($detail['sponsor_id']) {
            $Sponsors = new Sponsors();
            //获取赞助商名称
            $sponsorname = $Sponsors->oneDetail(['id' => $detail['sponsor_id']]);
            $detail['sp_name'] = $sponsorname['sp_name'];
            $detail['jump_url'] = $sponsorname['jump_url'] ?: '';//跳转地址
            $detail['jump_type'] = $sponsorname['jump_type'];//0小程序；1网站；2公众号
            $detail['sp_name_url'] = $sponsorname['sp_img']; //赞助商图片
        } else {
            if ($detail['user_id']) {
                //个人发起
                $usermsg = $this->usersbyid([$detail['user_id']], 'head_img,nick_name');
                $detail['sp_name'] = $usermsg ? $usermsg[0]['nick_name'] : "";
                $detail['sp_name_url'] = $usermsg ? $usermsg[0]['head_img'] : "";
            } else {
                $detail['sp_name'] = "";
            }
        }
        //参与总人数
        $joincount = Db::table('luck_join')
            ->where('prize_id', $prizeid)
            ->count();
        $detail['join_count'] = $joincount;
        //获取六个参与人头像
        $userids = Db::table('luck_join')
            ->field('user_id')
            ->where('prize_id', $prizeid)
            ->order('join_time desc')
            ->limit(6)
            ->column('user_id');
        $sixjoin = $this->usersbyid($userids, 'id,head_img');
        $detail['six_join'] = $sixjoin;
        if ($detail['is_join']) {
            //用户已经参与过了,
            if ($detail['prize_type'] == 0) {
                //查询幸运指数,已经邀请人
                $invitids = Db::table('luck_index')
                    ->field('invit_user_id')
                    ->where('user_id', $userid)
                    ->where('prize_id', $prizeid)
                    ->limit(10)
                    ->column('invit_user_id');
                //邀请人总数
                $invit_users_count = Db::table('luck_index')
                    ->where('user_id', $userid)
                    ->where('prize_id', $prizeid)
                    ->count();
                $invitusers = $this->usersbyid($invitids, 'id,head_img,nick_name');
                $detail['invit_users'] = $invitusers;
                $detail['invit_users_count'] = $invit_users_count;
                //当前幸运总指数
                $detail['lucky_index'] = $invit_users_count;
            }
        }
        $is_join_invit = 0;
        if ($detail['prize_type']) {
            //查看分享的人有没有参与当前抽奖
            if ($inviteid != $userid && $userid) {
                //查询此用户是否参与
                $is_join_invit = $this->isjoin($inviteid, $prizeid);
                $detail['is_join_invit'] = $is_join_invit ? 1 : 0;
            }
            if(empty($is_join_invit)) {
                $inviteid = $userid;
            }
            //获取队长
            $captainid = Db::table('luck_team')
                ->field('captain_id')
                ->where('prize_id', $prizeid)
                ->where('user_id', $inviteid)
                ->find();
            $detail['is_same_team'] = 0;
            if ($inviteid == $userid) {
                $detail['is_same_team'] = 1;
            }
            if ($captainid) {
                $iscaptainid = Db::table('luck_team')
                    ->field('captain_id')
                    ->where('prize_id', $prizeid)
                    ->where('user_id', $userid)
                    ->find();
                //查看当前用户和邀请人是不是一个队
                if ($iscaptainid['captain_id'] == $captainid['captain_id']) {
                    $detail['is_same_team'] = 1;
                }
            }
            if ($captainid) {
                //队员id
                $memberids = Db::table('luck_team')
                    ->field('user_id')
                    ->where('prize_id', $prizeid)
                    ->where('captain_id', $captainid['captain_id'])
                    ->column('user_id');
            } else {
                if ($inviteid != $userid) {
                    if ($is_join_invit) {
                        //还没组队,组员是他自己
                        $memberids = $inviteid;
                    } else {
                        if ($is_join) {
                            $memberids = $userid;
                        } else {
                            $memberids = 0;
                        }
                    }

                } else {
                    if ($is_join) {
                        $memberids = $userid;
                    } else {
                        $memberids = 0;
                    }

                }
            }
            $teammembers = $this->usersbyid($memberids, 'id,head_img,nick_name');
            $detail['team_members'] = $teammembers;
        }
        if ($detail['is_open']) {
            //查看当前用户是否中奖
            $iswinner=Db::table('luck_join')
                ->field('user_id,is_win,is_luckiest')
                ->where('user_id',$userid)
                ->where('prize_id', $prizeid)
                ->where('is_win', 'in', [1, 2])
                ->find();
            $detail['own_win_status']=array(
                'is_win'=>$iswinner?1:0,
                'is_received'=>$iswinner['is_win'] == 2 ? 1 : 0,
                'is_luckiest'=>$iswinner['is_luckiest'] ? 1 : 0
            );
            //获取中奖名单
            $winnerids = Db::table('luck_join')
                ->field('user_id')
                ->where('prize_id', $prizeid)
                ->where('is_win', 'in', [1, 2])
                ->limit(5)
                ->column('user_id');
            $winners = $this->usersbyid($winnerids, 'id,head_img,nick_name');
            for ($i = 0; $i < count($winners); $i++) {
                $isling = Db::table('luck_join')
                    ->field('user_id,is_win,is_luckiest')
                    ->where('user_id', $winners[$i]['id'])
                    ->where('prize_id', $prizeid)
                    ->find();
                $winners[$i]['is_received'] = $isling['is_win'] == 2 ? 1 : 0;
                $winners[$i]['is_luckiest'] = $isling['is_luckiest'] ? 1 : 0;

            }
            $detail['winners'] = $winners;
            //获取中奖总人数
            $winnercount = Db::table('luck_join')
                ->field('user_id')
                ->where('prize_id', $prizeid)
                ->where('is_win', 'in', [1, 2])
                ->count();
            $detail['winner_count'] = $winnercount;
        }
        return $detail;
    }

    /**
     * 中奖者名单
     * @param $prizeid
     */
    public function prizewinners($prizeid,$cpage)
    {
        //获取中奖名单
        $winnerids = Db::table('luck_join')
            ->field('user_id')
            ->where('prize_id', $prizeid)
            ->where('is_win', 'in', [1, 2])
            ->page($cpage, 80)
            ->column('user_id');
        $winners = $this->usersbyid($winnerids, 'id,head_img,nick_name');
        for ($i = 0; $i < count($winners); $i++) {
            $isling = Db::table('luck_join')
                ->field('user_id,is_win,is_luckiest')
                ->where('user_id', $winners[$i]['id'])
                ->where('prize_id', $prizeid)
                ->find();
            $winners[$i]['is_received'] = $isling['is_win'] == 2 ? 1 : 0;
            $winners[$i]['is_luckiest'] = $isling['is_luckiest'] ? 1 : 0;
        }
        return $winners;
    }

    /**
     * 用户得幸运指数邀请的人
     * @param $userid
     * @param $prizeid
     * @param $cpage
     */
    public function luckstars($userid,$prizeid,$cpage)
    {
        $invitids = Db::table('luck_index')
            ->field('invit_user_id')
            ->where('user_id', $userid)
            ->where('prize_id', $prizeid)
            ->page($cpage, 80)
            ->column('invit_user_id');
        $invitusers = $this->usersbyid($invitids, 'id,head_img,nick_name');
        return $invitusers;
    }

    /**
     * 用户参与抽奖
     * @param $userid
     * @param $prizeid
     */
    public function userjoin($userid,$prizeid,$inviteid=0,$formid)
    {
        $Luckteam = new Luckteam();
//        $result = array('members' => [], 'result' => 0, 'winners' => []);
        $result = array('result' => 0);
        $prize = Db::table('luck_prizes')
            ->field('prize_type,is_open,prize_num,full_num,prize_title')
            ->where('id', $prizeid)
            ->find();
        if ($prize && $prize['is_open'] == 0) {
            $isjoin = $this->isjoin($userid, $prizeid);
            if ($isjoin) {
                //已经参与过,
//                $result = array('members' => [], 'result' => 1, 'winners' => []);
                $result = array('result' => 1);
            } else {
                $fulljoin = 0;
                //检查组队情况是否满员
                if ($prize['prize_type'] == 1) {
                    //获取团队队长id
                    $team = $Luckteam->oneDetail(['prize_id' => $prizeid, 'user_id' => $inviteid]);
                    if (empty($team)) {
                        $teamcount = 1;
                    } else {
                        $manyuancapid = $team['captain_id'];
                        //查询队里总数
                        $teamcount = Db::table('luck_team')
                            ->where('prize_id', $prizeid)
                            ->where('captain_id', $manyuancapid)
                            ->count();

                    }
                    if ($teamcount >= $prize['prize_num']) {
                        //已满员,不能参与抽奖
                        $fulljoin = 1;
                    }
                }
                if (empty($fulljoin)) {
                    $data = array(
                        'user_id' => $userid,
                        'prize_id' => $prizeid,
                        'join_time' => time(),
                        'is_win' => 0
                    );
                    Db::table('luck_join')
                        ->insert($data);
                }
                //更新formid
                Db::table('luck_join')
                    ->where('user_id', $userid)
                    ->where('prize_id', $prizeid)
                    ->update(['formid' => $formid]);
                if ($prize['prize_type'] == 0) {
                    //自己参与过给自己加幸运指数
                    $this->addluckindex($userid, $userid, $prizeid);
                }
                if ($inviteid) {
                    //查看当前用户是否参与当前抽奖
                    $isjoin = Db::table('luck_join')
                        ->where('user_id', $inviteid)
                        ->where('prize_id', $prizeid)
                        ->find();
                    if ($isjoin) {
                        //说明参与过了
                        //说明是被人邀请参加的
                        if ($prize['prize_type'] == 0) {
                            //普通抽奖,给邀请人增加幸运指数
                            $resultnum = $this->addluckindex($userid, $inviteid, $prizeid);
                            $result = array('members' => [], 'result' => $resultnum, 'winners' => []);
                        } else {
                            //组团抽奖,加入战队
                            $result = $this->jointeam($userid, $inviteid, $prizeid, $team, $fulljoin);
                        }
                    }
                }
                //满多少人自动开奖,处理开奖
                $winners = $this->prizeopen($prize, $prizeid);
//                $result['winners'] = $winners;
            }
        } else {
            //抽奖已结束
//            $result = array('members' => [], 'result' => 2, 'winners' => []);
            $result = array('result' => 2);
        }
        return $result;
    }

    /**
     * 获取某个抽奖的参与用户
     * @param $prizeid
     * @param $cpage
     */
    public function joinusers($prizeid,$cpage=1)
    {
        $joinids = Db::table('luck_join')
            ->field('user_id')
            ->where('prize_id', $prizeid)
            ->page($cpage, 80)
            ->order('id desc')
            ->column('user_id');
        $join_users = $this->usersbyid($joinids, 'id,head_img');
        return $join_users;
    }

    /**
     * 获取中奖者收货列表
     * @param $userid 用户id
     * @param $prizeid 抽奖id
     */
    public function winneraddr($userid,$prizeid,$cpage)
    {
        $isown = Db::table('luck_prizes')
            ->where('id', $prizeid)
            ->where('user_id', $userid)
            ->find();
        if ($isown) {
            if ($isown['is_open'] == 0) {
                //还未开奖
                $result = array('result' => 2, 'addrs' => []);
            } else {
                $addrids = Db::table('luck_join')
                    ->field('addr_id,user_id')
                    ->where('prize_id', $prizeid)
                    ->where('is_win', 'in', [1, 2])
                    ->page($cpage, 10)
                    ->select();
                for ($i = 0; $i < count($addrids); $i++) {
                    $addr = Db::table('luck_address')
                        ->field('consignee,link_phone,link_area,link_address')
                        ->where('id', $addrids[$i]['addr_id'])
                        ->find();
                    $addrids[$i]['is_overdue'] = 0;
                    if ($addr) {
                        $addrids[$i]['consignee'] = $addr['consignee'];
                        $addrids[$i]['link_phone'] = $addr['link_phone'];
                        $addrids[$i]['link_area'] = $addr['link_area'];
                        $addrids[$i]['link_address'] = $addr['link_address'];
                    } else {
                        $addrids[$i]['consignee'] = "";
                        $addrids[$i]['link_phone'] = "";
                        $addrids[$i]['link_area'] = "";
                        $addrids[$i]['link_address'] = "";
                        //用户没领奖,查看是否过期
                        $deadline = strtotime("+3 days", $isown['open_time']);
                        if (time() > $deadline) {
                            //过期了
                            $addrids[$i]['is_overdue'] = 1;
                        }
                    }
                    //获取当前用户的昵称和头像
                    $user = Db::table('luck_users')
                        ->field('head_img,nick_name')
                        ->where('id', $addrids[$i]['user_id'])
                        ->find();
                    $addrids[$i]['head_img'] = $user['head_img'];
                    $addrids[$i]['nick_name'] = urldecode($user['nick_name']);
                }
                $result = array('result' => 0, 'addrs' => $addrids);
            }

        } else {
            //这个抽奖不是此用户发起的,不能查看
            $result = array('result' => 1, 'addrs' => []);
        }
        return $result;
    }


    /**
     * 中奖者领取奖品
     * @param $userid 用户id
     * @param $prizeid 抽奖id
     * @param $addrid 地址id
     */
    public function receiveprize($userid,$prizeid,$addrid)
    {
        $result = 0;
        //查看当前用户是否中奖
        $windata = Db::table('luck_join')
            ->where('user_id', $userid)
            ->where('prize_id', $prizeid)
            ->where('is_win', 'in', [1, 2])
            ->find();
        if ($windata) {
            if ($windata['is_win'] == 2) {
                //已经领过了
                $result = 2;
            } else {
                Db::table('luck_join')
                    ->where('user_id', $userid)
                    ->where('prize_id', $prizeid)
                    ->update(['is_win' => 2, 'addr_id' => $addrid]);
            }
        } else {
            //么有中奖
            $result = 1;
        }
        return $result;
    }

    /**
     * 创建奖品
     * @param $data
     * @return int|string
     */
    public function createprize($data)
    {
        $prizeid = Db::table('luck_prizes')
            ->insertGetId($data);
        return $prizeid;
    }



    /**
     * 根据id集合获取用户信息
     * @param $userids  用户id集合
     * @param $fields 查询字段信息
     */
    function usersbyid($userids,$fields)
    {
        $data = [];
        if ($userids) {
            $data = Db::table('luck_users')
                ->field("$fields")
                ->where('id', 'in', $userids)
                ->order('id', $userids)
                ->select();
            if(strstr($fields, 'nick_name')){
                for ($i=0;$i<count($data);$i++){
                    $data[$i]['nick_name']=urldecode($data[$i]['nick_name']);
                }
            }
        }
        return $data;
    }

    /**
     * 奖品的通用处理
     * @param $prizedata 数据集合
     * @param $is_sponsor 0需要显示赞助商,1不需要
     * @param $userid 用户id
     */
    function commonHandle($prizedata,$is_sponsor=0,$userid=0)
    {
        $result = array();
        foreach ($prizedata as $item) {
            if ($item['full_num']) {
                $item['open_time'] = "参与人数达到{$item['full_num']}人自动开奖";
            } else {
                $item['open_time'] = date("m月d日 H:i", $item['open_time']) . " 开奖";
            }
            if (empty($is_sponsor)) {
                if ($item['sponsor_id']) {
                    $Sponsors=new Sponsors();
                    //获取赞助商名称
                    $sponsorname=$Sponsors->oneDetail(['id'=>$item['sponsor_id']]);
                    $item['sp_name'] = $sponsorname['sp_name'] . "赞助";
                } else {
                    $item['sp_name'] = "";
                }
                unset($item['sponsor_id']);
            }
            unset($item['full_num']);
            if ($userid) {
                //传了用户id,查询当前用户是否参与
                $is_join = $this->isjoin($userid, $item['id']);
                $item['is_join'] = $is_join ? 1 : 0;
            }
            $result[] = $item;
        }
        return $result;
    }




    /**
     * 用户是否参与抽奖
     * @param $userid
     * @param $prizeid
     */
    function isjoin($userid,$prizeid)
    {
        $isjoin = Db::table('luck_join')
            ->where('user_id', $userid)
            ->where('prize_id', $prizeid)
            ->find();
        return $isjoin;
    }

    /**
     * 增加幸运指数
     * @param $userid  用户id
     * @param $invituserid  邀请人id(此id邀请的userid)
     */
    function addluckindex($userid,$inviteid,$prizeid)
    {
        //是否增加过
        $isadd = Db::table('luck_index')
            ->where('user_id', $inviteid)
            ->where('prize_id', $prizeid)
            ->where('invit_user_id', $userid)
            ->find();
        if (empty($isadd)) {
            $luckindex = array(
                'user_id' => $inviteid,
                'prize_id' => $prizeid,
                'index_num' => 1,
                'invit_user_id' => $userid,
                'create_time' => time()
            );
            Db::table('luck_index')
                ->insert($luckindex);
        }
        return 0;
    }

    /**
     * 加入团队
     * @param $userid 用户id
     * @param $inviteid 邀请人id(此id邀请的userid)
     * @param $prizeid 奖品id
     * @param $prizenum 奖品数量
     */
    function jointeam($userid,$inviteid,$prizeid,$team,$fulljoin)
    {
        $result = 0;
        //查询是否已经加入了
        $Luckteam = new Luckteam();
        $isjointeam = $Luckteam->oneDetail(['prize_id' => $prizeid, 'user_id' => $userid]);
        if (empty($isjointeam)) {
            if (empty($team)) {
                $captain_id = $inviteid;
                if(empty($fulljoin)){
                    //说明是新组队的,队长先创建团队
                    $inserteam = array(
                        'prize_id' => $prizeid,
                        'captain_id' => $inviteid,
                        'user_id' => $inviteid,
                        'create_time' => time()
                    );
                    $Luckteam->addOne($inserteam);
                }
            } else {
                $captain_id = $team['captain_id'];
            }
            if(empty($fulljoin)){
                //用户加入团队
                $inserteam = array(
                    'prize_id' => $prizeid,
                    'captain_id' => $captain_id,
                    'user_id' => $userid,
                    'create_time' => time()
                );
                $Luckteam->addOne($inserteam);
            }else{
                //组队完成,不能再加入了
                $result = 3;
            }
        }
        //获取队员
//        $memberids = Db::table('luck_team')
//            ->field('user_id')
//            ->where('prize_id', $prizeid)
//            ->where('captain_id', $captain_id)
//            ->column('user_id');
//        $teammembers = $this->usersbyid($memberids, 'id,head_img,nick_name');
        return array('members' => [], 'result' => $result,'winners'=>[]);
    }


    /**
     * 奖品开奖
     * @param $prize 奖品信息
     * @param $prizeid 奖品id
     * @return
     */
    function prizeopen($prize,$prizeid)
    {
        $result = [];
        if ($prize['full_num']) {
            //说明是满多少人自动开奖
            //查询当前参与人数
            $joincount = Db::table('luck_join')
                ->where('prize_id',$prizeid)
                ->count();
            if ($joincount == $prize['full_num']) {
                //说明人数够了,开奖
                if (empty($prize['prize_type'])) {
                    //查看今天为止15天内中奖的人,过滤掉
                    $endtime=time();
                    $startime=strtotime("-15 day",$endtime);
                    $outids=Db::table('luck_join')
                        ->field('user_id')
                        ->where("join_time>=$startime and join_time<=$endtime")
                        ->where('is_win', 'in', [1, 2])
                        ->group('user_id')
                        ->column('user_id');
                    if(empty($outids)){
                        $outids=0;
                    }
                    //中奖人
                    $mwinnerids = Db::table('luck_index')
                        ->field('SUM(index_num) AS index_num,user_id')
                        ->where('prize_id', $prizeid)
                        ->where('user_id','not in',$outids)
                        ->group('user_id')
                        ->order('index_num desc')
                        ->limit($prize['prize_num'])
                        ->select();
                    $winnerids="";
                    for ($i=0;$i<count($mwinnerids);$i++){
                        $winnerids[]=$mwinnerids[$i]['user_id'];
                    }
                } else {
                    //组团,随机取一个人
                    $randnum=mt_rand(1,$joincount);
                    $winnerid=Db::table('luck_join')
                        ->field('user_id')
                        ->where('prize_id',$prizeid)
                        ->page($randnum,1)
                        ->column('user_id');
                    //查看当前中奖人有没有组队
                    $winnteam=Db::table('luck_team')
                        ->field('captain_id')
                        ->where('prize_id', $prizeid)
                        ->where('user_id',$winnerid[0])
                        ->find();
                    if($winnteam){
                        //组队了
                        //获取中奖组员
                        $winnerids = Db::table('luck_team')
                            ->field('user_id')
                            ->where('prize_id', $prizeid)
                            ->where('captain_id', $winnteam['captain_id'])
                            ->column('user_id');
                        //设置运气爆棚人
                        Db::table('luck_join')
                            ->where('prize_id', $prizeid)
                            ->where('user_id', $winnerid[0])
                            ->update(['is_luckiest' => 1]);

                    }else{
                        $winnerids=$winnerid;
                    }
                }
//                $winners = $this->usersbyid($winnerids, 'id,head_img,nick_name');
                //给所有参与人发送模板消息
                $joinids = Db::table('luck_join')
                    ->field('user_id')
                    ->where('prize_id',$prizeid)
                    ->column('user_id');
                $this->sendwechatmsg($joinids,$prize['prize_title'],$prizeid);
                //将该奖品改为已开奖
                Db::table('luck_prizes')
                    ->where('id', $prizeid)
                    ->update(['open_time' => time(), 'is_open' => 1]);
                //将中奖人设置为已中奖
                Db::table('luck_join')
                    ->where('prize_id', $prizeid)
                    ->where('user_id', 'in', $winnerids)
                    ->update(['is_win' => 1]);
//                $result = $winners;
            }
        }
        return $result;
    }

    /**
     * 给中奖人发送模板消息
     */
    function sendwechatmsg($winnerids,$prizename,$prizeid=0)
    {
        $winners = $this->usersbyid($winnerids, 'id,openid');
        for ($i = 0; $i < count($winners); $i++) {
            //获取formid
            $formid = Db::table('luck_join')
                ->field('formid')
                ->where('user_id', $winners[$i]['id'])
                ->where('prize_id', $prizeid)
                ->value('formid');
            $winners[$i]['formid'] = $formid;
        }
        $content = array(
            "keyword1" => array(
                'value' => $prizename
            ),
            "keyword2" => array(
                'value' => "您参与的抽奖活动正在开奖，赶紧戳进来看看大奖名单"
            ),
        );
        //发送小程序模板消息
        $page = "pages/detail/main?prizeid=$prizeid";//消息点击跳转地址
        Util::send_prize_template($winners, $content, $page);
    }

    //生成二维码
    function wechatcode($userid,$prizeid)
    {
        $param = json_encode(array("page" => "pages/detail/main","scene"=>"prizeid=$prizeid&userid=$userid"));
        $base64_image = Util::sp_qrcode_create($param);
        return $base64_image;
    }
}